<?php

namespace App\Admin\Controllers;

use App\Admin\Handers\MaterialHander;
use App\Models\Goods;
use App\Models\GoodsClassify;
use App\Models\Material;
use App\Models\PrintArea;
use App\Models\PurchaseToMaterial;
use App\Models\RecordMaterial;
use App\Models\Sharp;
use App\Models\StoreDetail;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Illuminate\Database\Eloquent\Builder;

class GoodsController extends AdminController
{
	/**
	 * Title for current resource.
	 *
	 * @var string
	 */
	protected $title = '商品';
	
	protected $goodsStatus = [
		'on' => ['value' => 1, 'text' => '正常', 'color' => 'success'],
		'off' => ['value' => 2, 'text' => '下架', 'color' => 'danger'],
	];
	
	protected $onlyShowPackage = [
		'on' => ['value' => 1, 'text' => '是', 'color' => 'success'],
		'off' => ['value' => 2, 'text' => '否', 'color' => 'danger'],
	];
	
	/**
	 * Make a grid builder.
	 *
	 * @return Grid
	 */
	protected function grid()
	{
		$grid = new Grid(new Goods());
		
		$grid->model()->orderByDesc('created_at');
		$grid->number('序号');
		$grid->rows(function ($row, $number) {
			$row->column('number', $number + 1);
		});
		$grid->column('name', __('Name'));
		$grid->column('images_url', __('Images url'))
			->image('', '50');
		$grid->column('price', __('Price'))->display(function ($data) {
			return '￥'. $data;
		});
		$grid->column('stock', __('Stock'))->sortable();
		$grid->column('sell', __('Sell'))->sortable();
		$grid->column('sort', __('Sort'));
		$grid->column('goods_number', __('Goods number'));
		$grid->column('status', __('Status'))->switch($this->goodsStatus);
		$grid->column('only_show_package', '小程序端是否显示')->switch($this->onlyShowPackage);
		$grid->column('created_at', __('Created at'))->sortable();

		// 筛选
		$grid->filter(function ($filter) {
			
			// 去掉默认的id过滤器
			$filter->disableIdFilter();
			
			// 在这里添加字段过滤器
			$filter->like('name', __('Name'));
			
			// 范围过滤器，调用模型的`onlyTrashed`方法，查询出被软删除的数据。
			// $filter->scope('trashed', '回收站')->onlyTrashed();
		});
		
		$grid->actions(function ($action) {
			$action->disableView();
		});
		return $grid;
	}
	
	/**
	 * Make a show builder.
	 *
	 * @param mixed $id
	 * @return Show
	 */
	protected function detail($id)
	{
		$show = new Show(Goods::findOrFail($id));
		
		$show->field('id', __('Id'));
		$show->field('name', __('Name'));
		$show->field('images_url', __('Images url'));
		$show->field('price', __('Price'));
		$show->field('stock', __('Stock'));
		$show->field('sell', __('Sell'));
		$show->field('sort', __('Sort'));
		$show->field('describe', __('Describe'));
		$show->field('goods_number', __('Goods number'));
		$show->field('status', __('Status'));
		$show->field('created_at', __('Created at'));
		$show->field('updated_at', __('Updated at'));
		$show->field('deleted_at', __('Deleted at'));
		
		return $show;
	}
	
	/**
	 * Make a form builder.
	 *
	 * @return Form
	 */
	protected function form()
	{
		$form = new Form(new Goods());
		
		$form->hidden('store_id')->default(Admin::user()->store_id);
		$form->text('name', __('Name'))
			->rules('required|max:100');
		
		$form->multipleSelect('classify', '分类')
			->options(GoodsClassify::where('store_id', Admin::user()->store_id)->pluck('title', 'id'))
			->rules('required');
		
		$form->multipleSelect('printarea', '打印区域')
			->options(PrintArea::where('store_id', Admin::user()->store_id)->pluck('name', 'id'))
			->required();
		
		$form->image('images_url', __('Images url'))
			->removable()
			->uniqueName()
			->rules('required');
		
		$form->currency('price', __('Price'))->symbol('￥')
			->rules('required|min:1');
		
		$form->number('stock', __('Stock'))
			->default(1)
			->rules('min:1');
		
		$form->number('sell', __('Sell'))
			->default(0)
			->rules('min:1');
		
		$form->number('sort', __('Sort'))
			->default(1)
			->rules('min:1');
		
		$form->editor('describe', __('Describe'));
		
		$form->text('goods_number', __('Goods number'))
            ->append('<a type="button" id="get_number">生成编码</a>')
            ->setScript("
		 $('#get_number').on('click', function() {
		    $.ajax({
		        type:'post',
		        url: '".Route('goodsNumber')."',
		        data:{
		            _token:LA.token,
		        },
		        success: function (res) {
		            $('#goods_number').val(res);
		            toastr.success('生成成功');
		        }
		    });
		});")->readonly()
			->rules('required|unique:goods,goods_number,{{id}}');
		
		$form->switch('status', __('Status'))
			->states($this->goodsStatus)->default(2);
		$form->switch('only_show_package', '小程序端是否显示')
			->states($this->onlyShowPackage)->default(1);
		$form->switch('storaged', '可以存储')->states($this->onlyShowPackage)->default(2);
		
		$form->hasMany('goodstomaterial', '所需材料', function (Form\NestedForm $form) {
			$form->select('material_id', '材料')
                  ->options(Material::all()->pluck('name', 'id'));
			$form->number('number', '数量')->default(1);
		});
		
		$msg = '成功';
		$type = 'success';
		$form->confirm('如过更改了材料会删除所有规格属性，确定更新吗？', 'edit');
		 //计算材料用量与最低价格并且减少材料批次库存
		$form->saving(function (Form $form) use ($msg, $type){
			// 判断是否参与秒杀活动
			$res = Sharp::checkThisGoodsIsInSharp(Admin::user()->store_id, $form->model()->id);
			if ($res) {
				$this->showMsg('正在参与秒杀暂不能修改', 'error', $form->model()->id);
			}
			// 删除关联关系，返回库存
			if($form->model()->id){
				$goods = Goods::with(['cutMaterials'])->find($form->model()->id);

				Goods::returnStock($goods->toArray()['cut_materials'], $form->model()->stock);
				//$goods->cutMaterials()->detach();
			}

			$form->model()->store_id = Admin::user()->store_id;
			$numbers = [];
			$stock = [];
			$initPrice = [];
			$needs = [];
			$need = [];

			if (!empty($form->goodstomaterial)) {
				foreach ($form->goodstomaterial as $k => $v) {
					$material_id[] = $v['material_id'];
					$numbers[] = $v['number'];

					// 搜索各种材料库存
					$stock[] = PurchaseToMaterial::where('material_id', $v['material_id'])
						->whereHas('purchase', function (Builder $query) {
							$query->where('store_id', Admin::user()->store_id)
								->where('status', 2);
						})->where('stock', '>', 0)
						->where('status', '1')
						->sum('stock');
					// 搜索各种材料单价
					$initPrice[] = PurchaseToMaterial::where('material_id', $v['material_id'])
							->whereHas('purchase', function (Builder $query) {
								$query->where('store_id', Admin::user()->store_id);
							})->orderBy('created_at', 'desc')
							->first('unit_price');
					// 应当减少的库存
					$need[] = $v['number'] * $form->stock;
					$needs[$v['material_id']] = $v['number'] * $form->stock;
				}
				//ksort($need);
				//dd($stock, $need);
				$mini = MaterialHander::minimun_stock($stock, $numbers);

				if ($form->stock > $mini) {
					admin_toastr('当前材料数量不支持设置商品库存数量为' . $form->stock . '，应当小于等于' . $mini, 'warning');
					$goods->cutMaterials()->detach();
					return redirect()->route('store-goods.edit', ['store_good' => $form->model()->id]);
					//throw new \Exception('当前材料数量不支持设置商品库存数量为' . $form->stock . '，应当小于等于' . $mini);
				}
				// 计算最小可设置单价, 查询分账百分比
				$sharingPercent = StoreDetail::where('store_id', Admin::user()->store_id)
					->first('sharing_percent');

				$limitPrice = MaterialHander::limitPrice($initPrice, $numbers, empty($sharingPercent) ? 0 : $sharingPercent['sharing_percent']);
				if ($form->price < $limitPrice) {
					admin_toastr('建议价格为'.$limitPrice.'以上', 'warning');
					$goods->cutMaterials()->detach();
					return redirect()->route('store-goods.edit', ['store_good' => $form->model()->id]);
				}

				// 减少材料批次库存 库存 $stock $need
				$materials = PurchaseToMaterial::whereHas('purchase',function (Builder $query) {
					            $query->where('store_id', Admin::user()->store_id)
						            ->where('status', 2);
					        })->whereIn('material_id', $material_id)
						        ->where('status', 1)
							->orderBy('material_id')
							->get();
				$stock = $materials->groupBy('material_id')->toArray();
				//ksort($needs);
				//dd($material_id, $stock, $materials);
				//dd($stock, $needs);
				foreach ($needs as $k => $v){
						$reduceStock = MaterialHander::deduction_stock($stock[$k], $v);

						foreach ($reduceStock as $key => $value)
						{
							$pToMaterial = PurchaseToMaterial::find($value['id']);
							$pToMaterial->stock = $value['stock'];
							$pToMaterial->sell = $value['sell'];
							$pToMaterial->status = $value['status'];

							$res  = $pToMaterial->save();
						}
						// 生成消耗记录
						$record = new RecordMaterial();
						$record->store_id = Admin::user()->store_id;
						$record->purchase_to_material_id= $pToMaterial->id;
						$record->material_id = $pToMaterial->material_id;
						$record->number= $v;
						$record->description= '生成'.$form->name;
						$record->style= 2;
						$record->type= 2;

						$record->save();
				}
			}
		});
		$form->saved(function (Form $form) use ($msg, $type){
			
			admin_toastr($msg, $type);
			return redirect()->route('store-goods.edit', ['store_good' => $form->model()->id]);
		});
		return $form;
	}
	
	// 商品编号
	public function goodsNumber()
	{
		return date('YmdHi',time()).random_int(0, 9).random_int(0, 9);
	}
	
	public function destroy($id)
	{
		$res = Sharp::checkThisGoodsIsInSharp(Admin::user()->store_id, $id);
		if ($res) {
			return response()->json(['status' => false, 'message' => '该商品正在参加秒杀活动，暂不能删除']);
		}
		
		return $this->form()->destroy($id);
	}
	
	public function showMsg($msg, $type, $goods_id, $goods = [])
	{
		admin_toastr($msg, $type);
		
		if (!empty($goods)) {
			$goods->cutMaterials()->detach();
		}

		return redirect()->route('store-goods.edit', ['store_good' => $goods_id]);
	}
}
